import React, { useState } from 'react'
import { MenuFoldOutlined, MenuUnfoldOutlined, UserOutlined } from '@ant-design/icons'
import { Layout, Button, theme, Avatar, Drawer, Collapse, CollapseProps, Divider, Form, Input, Upload, GetProp, UploadProps, message, Spin } from 'antd'
import { Navigate, Outlet, useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'
import VSider from './components/VSider'
import { TREEMENUDATA1,TREEMENUDATA2 } from './utils/constant'
import './App.css'
import axios from 'axios'
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}

/** 检查上传格式 */
const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!')
  }
  return isJpgOrPng && isLt2M
}
const { Header, Content } = Layout
const App = () => {
  const token = sessionStorage.getItem('token')
  // const token ="xxxx";
  const user_id = sessionStorage.getItem('user_id')
  const user_name = sessionStorage.getItem('user_name')
  const avatar = sessionStorage.getItem('avatar')
  const type = sessionStorage.getItem('type');
  console.log(avatar, 'avatar')
  const navigate = useNavigate()
  const { checkedTab } = useSelector((state: any) => state.home)
  const [collapsed, setCollapsed] = useState(false)
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState<string | null>(avatar)

  const handleUpload = async (file: string | Blob) => {
    setLoading(true)
    // 构建FormData对象
    const formData = new FormData()
    formData.append('file', file)
    // 发送POST请求到后端
    await axios
      .post('/api/avatar/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token
        }
      })
      .then(res => {
        if (res.data.result === 'SUCCESS') {
          console.log('上传成功:', res.data.data)
          setImageUrl(res.data.data)
          console.log(imageUrl, 'imageUrl')
          message.success('上传成功')
        }
      })
      .catch(error => {
        console.error('上传失败:', error)
        message.error('上传失败')
      })
      .finally(() => {
        setLoading(false)
      })
  }

  const showDrawer = () => {
    setOpen(true)
  }

  // 生成全部路由
  const TreeMenuData = type=='1'?TREEMENUDATA1.map(firstItem => {
    const children = firstItem.children
    return {
      ...firstItem,
      key: firstItem.value,
      icon: <i className={`iconfont icon-${firstItem.type}`}></i>,
      label: firstItem.title,
      children: children ? children.map(secondItem => ({ ...secondItem, key: firstItem.value + '/' + secondItem.value, icon: <i className={`iconfont icon-${secondItem.type}`}></i>, label: secondItem.title, value: firstItem.value + '/' + secondItem.value })) : undefined
    }
  }):TREEMENUDATA2.map(firstItem => {
    const children = firstItem.children
    return {
      ...firstItem,
      key: firstItem.value,
      icon: <i className={`iconfont icon-${firstItem.type}`}></i>,
      label: firstItem.title,
      children: children ? children.map(secondItem => ({ ...secondItem, key: firstItem.value + '/' + secondItem.value, icon: <i className={`iconfont icon-${secondItem.type}`}></i>, label: secondItem.title, value: firstItem.value + '/' + secondItem.value })) : undefined
    }
  })

  return (
    <Layout>
      {token === null ? (
        <Navigate to={'/login'}></Navigate>
      ) : (
        <>
          <VSider menuList={TreeMenuData} collapsed={collapsed} />
          <Layout>
            <Header
              style={{
                padding: 0,
                background: '#fff',
                overflow: 'auto',
                position: 'sticky',
                left: 0,
                top: 0,
                zIndex: 2,
                display: 'flex',
                justifyContent: 'space-between'
              }}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center'
                }}>
                <Button
                  type="text"
                  icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                  onClick={() => {
                    setCollapsed(!collapsed)
                  }}
                  style={{
                    fontSize: '18px',
                    height: 60,
                    marginRight: 10
                  }}
                />
                <span className="header-tab">{checkedTab}</span>
              </div>

              <div
                className="user-icon"
                onClick={() => {
                  showDrawer()
                }}>
                {imageUrl ? <Avatar src={imageUrl} /> : <UserOutlined />}
                <a>{user_id}</a>
              </div>
              <Drawer
                title="个人信息"
                onClose={() => {
                  setOpen(false)
                }}
                open={open}>
                {/* <Divider ><Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=1" /></Divider>
          <div className="user-avatar"></div>
           */}
                <div style={{ padding: '20px' }}>
                  <div style={{ textAlign: 'center' }}>
                    <Upload
                      name="avatar"
                      listType="picture-circle"
                      className="avatar-uploader"
                      showUploadList={false}
                      customRequest={({ file }) => handleUpload(file)}
                      beforeUpload={beforeUpload}

                      // https://api.dicebear.com/7.x/miniavs/svg?seed=1
                    >
                      <Spin spinning={loading}>{imageUrl ? <Avatar size={100} src={imageUrl} /> : <UserOutlined style={{ fontSize: '80px' }} />}</Spin>
                    </Upload>
                  </div>
                  <Form
                    name="basic"
                    initialValues={{ remember: true }}
                    onFinish={async ({ new_password }) => {
                      const params = { new_password: new_password, user_id: user_id }
                      await axios
                        .post(
                          '/api/edit_pwd',
                          { ...params },
                          {
                            headers: {
                              Authorization: token
                            }
                          }
                        )
                        .then(res => {
                          if (res.data.result === 'SUCCESS') {
                            message.success('密码修改成功')
                          }
                        })
                    }}
                    style={{ marginTop: '20px' }}>
                    <Form.Item label="工号" name="user_id">
                      <Input defaultValue={user_id!} disabled />
                    </Form.Item>

                    <Form.Item label="姓名" name="name">
                      <Input defaultValue={user_name!} disabled />
                    </Form.Item>

                    <Form.Item label="旧密码" name="password" rules={[{ required: true, message: '请输入旧密码!' }]}>
                      <Input.Password />
                    </Form.Item>

                    <Form.Item label="新密码" name="new_password" rules={[{ required: true, message: '请输入新密码!' }]}>
                      <Input.Password />
                    </Form.Item>

                    <Form.Item>
                      <Button type="primary" htmlType="submit">
                        保存密码
                      </Button>
                    </Form.Item>
                    <Divider />
                    <Form.Item>
                      <Button
                        onClick={() => {
                          navigate('/login')
                          sessionStorage.clear()
                        }}>
                        退出登录
                      </Button>
                    </Form.Item>
                  </Form>
                </div>
              </Drawer>
            </Header>
            <Content
              style={{
                margin: 0,
                padding: 0,
                minHeight: 560,
                background: '#fff'
                // borderRadius: borderRadiusLG,
              }}>
              <Outlet />
            </Content>
          </Layout>
        </>
      )}
    </Layout>
  )
}
export default App
